package com.xboss.tv.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hejunlin.tvsample.widget.AutoLayoutManager;
import com.hejunlin.tvsample.widget.MetroViewBorderImpl;
import com.xboss.tv.R;
import com.xboss.tv.adapter.NewsDataAdapter;
import com.xboss.tv.bean.Contacts;
import com.xboss.tv.bean.NewsBean;
import com.xboss.tv.listener.DataAPIListener;
import com.xboss.tv.net.DataAPIClient;
import com.xboss.tv.ui.UrlDataActivity;
import com.xboss.tv.util.DateFormatUtil;
import com.xboss.tv.view.SpaceItemDecoration;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017\7\23 0023.
 */

public class ChildDataFragment extends Fragment {

    private RecyclerView mRecyclerView;
    private MetroViewBorderImpl mMetroViewBorderImpl;
    private Activity activity;
    public StrProcessor parser;
    private OnDataFinishedListener mOnDataFinishedListener;

    public static interface StrProcessor {

        void OnParserJsonString(JSONObject response);
    }

    public static interface OnDataFinishedListener {
        void onPerformData();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.child_layout_content, container, false);

        activity = getActivity();

        parser = new StrProcessor() {
            @Override
            public void OnParserJsonString(JSONObject response) {
                parseJson(response);
            }
        };

        mOnDataFinishedListener = new OnDataFinishedListener() {
            @Override
            public void onPerformData() {
                initUI(view);
            }
        };

        initData(10, 0, "育儿");

        return view;
    }

    private void initUI(View view) {

        mMetroViewBorderImpl = new MetroViewBorderImpl(activity);
        mMetroViewBorderImpl.setBackgroundResource(R.drawable.border_color);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.child_recycler_view);

        GridLayoutManager gridlayoutManager = new AutoLayoutManager(activity, 2);
        gridlayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(gridlayoutManager);
        mRecyclerView.setFocusable(false);
        mMetroViewBorderImpl.attachTo(mRecyclerView);

        mRecyclerView.addItemDecoration(new SpaceItemDecoration(2,
                getResources().getDimensionPixelSize(R.dimen.padding_middle), true));

        NewsDataAdapter adapter = new NewsDataAdapter(activity, mNewsData);
        mRecyclerView.setAdapter(adapter);

        adapter.setOnMenuitemClickListener(new NewsDataAdapter.OnMenuitemClickListener() {
            @Override
            public void onItemClick(String url, int position) {
                if (Contacts.isLoad) {
                    Intent intent = new Intent(activity, UrlDataActivity.class);
                    intent.putExtra("url", url);
                    startActivity(intent);

                    Contacts.isLoad = false;
                }
            }

            @Override
            public void onBackClick() {
                activity.finish();
            }
        });
    }

    private void initData(int num, int start, String channelName) {

        Map<String, String> params = new LinkedHashMap<>();
        params.put("channel", channelName);
        params.put("num", num + "");
        params.put("start", start + "");
        params.put("appkey", Contacts.jd_key);

        DataAPIClient.doHttpRequest(activity, Contacts.jd_url, params, new DataAPIListener() {
            @Override
            public void onSuccess(JSONObject response) {
                parser.OnParserJsonString(response);
            }

            @Override
            public void onFailure(String errorMsg) {
                Toast.makeText(activity, "查询数据失败，失败数据为:" + errorMsg, Toast.LENGTH_SHORT).show();
                activity.finish();
            }
        });
    }

    private List<NewsBean> mNewsData;

    private void parseJson(JSONObject response) {

        JSONObject result1 = response.getJSONObject("result");
        JSONObject result2 = result1.getJSONObject("result");

        JSONArray list = result2.getJSONArray("list");

        mNewsData = new ArrayList<>();
        mNewsData.clear();

        for (int i = 0; i < list.size(); i++) {

            NewsBean bean = new NewsBean();

            JSONObject object = list.getJSONObject(i);
            bean.weburl = object.getString("weburl");
            bean.url = object.getString("url");
            bean.pic = object.getString("pic");
            bean.src = object.getString("src");
            bean.title = object.getString("title");

            String time = object.getString("time");

            long ctime = 0;
            try {
                ctime = DateFormatUtil.stringToLong(time, "yyyy-MM-dd HH:mm");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            bean.showtime = ctime;
            bean.time = time;

            mNewsData.add(bean);
        }

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mOnDataFinishedListener.onPerformData();
            }
        });
    }
}
